//
//  HOTAppDelegate.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-8-22.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTAppDelegate.h"
#import "HOTEntryViewController.h"
#import "HOTNavigationViewController.h"
#import "RootViewController.h"
#import "HOTUserInfo.h"
#import <GoogleMaps/GoogleMaps.h>
#import "APService.h"
#import "Harpy.h"
#import "HOTUtils.h"
#import "HOTMessageHandler.h"
#import "ImobileSdkAds/ImobileSdkAds.h"

@interface HOTAppDelegate () {
    
    
    id services_;
}
@end

@implementation HOTAppDelegate


-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    NSLog(@"获取推送出错");
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    if (launchOptions) {
        
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        [[HOTMessageHandler handler] handleMessageNotification:launchOptions];
    }
    
    //初始化
    [HOTConfig config];
    
    //注册谷歌地图的key
    [GMSServices provideAPIKey:kGOOGLE_MAP_API_KEY];
    services_ = [GMSServices sharedServices];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor blackColor];
    
    self.menuVC = [[HOTMenuViewController alloc] initWithNibName:@"HOTMenuViewController" bundle:nil];
    
//    self.entryVC = [[HOTEntryViewController alloc] initWithNibName:@"HOTEntryViewController" bundle:nil];
    
    //==================Admob start==================
    
    // バナー広告スポットの登録をします
    BOOL adResult = [ImobileSdkAds registerWithPublisherID:IMOBILE_SDK_ADS_PUBLISHER_ID
                                                  MediaID:IMOBILE_SDK_ADS_MEDIA_ID
                                                   SpotID:IMOBILE_SDK_ADS_SPOT_ID];
    if (!adResult) {
        NSLog(@"バナー広告スポットの登録に失敗しました。");
    }
    
    [ImobileSdkAds startBySpotID:IMOBILE_SDK_ADS_SPOT_ID];
    
    //==================Admob end=====================
    
    //==================版本更新 start==================
    // Set the App ID for your app
    [[Harpy sharedInstance] setAppID:@"932262009"];
    
    // Set the UIViewController that will present an instance of UIAlertController
    [[Harpy sharedInstance] setPresentingViewController:_window.rootViewController];
    
    /* (Optional) Set the Alert Type for your app
     By default, Harpy is configured to use HarpyAlertTypeOption */
    [[Harpy sharedInstance] setAlertType:HarpyAlertTypeOption];
    
    /* (Optional) If your application is not availabe in the U.S. App Store, you must specify the two-letter
     country code for the region in which your applicaiton is available. */
    [[Harpy sharedInstance] setCountryCode:@"JP"];
    
    // Perform check for new version of your app
    [[Harpy sharedInstance] checkVersion];
    
    //==================版本更新 end==================
    
    //RootViewController *rootVC = [[RootViewController alloc] initWithNibName:@"RootViewController" bundle:nil];
    
    //生成业种plist
    //[self createJobTypePlist];
    
    //生成都道府县的联动plist
    //[self createRegion];
    
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    
    //==============================JPush===============================================
    // Required
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                   UIRemoteNotificationTypeSound |
                                                   UIRemoteNotificationTypeAlert)
                                       categories:nil];
    [APService setupWithOption:launchOptions];
    
    
    
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    
    [defaultCenter addObserver:self selector:@selector(networkDidSetup:) name:kJPFNetworkDidSetupNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidClose:) name:kJPFNetworkDidCloseNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidRegister:) name:kJPFNetworkDidRegisterNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidLogin:) name:kJPFNetworkDidLoginNotification object:nil];
    
    [APService setTags:nil alias:[APService registrationID] callbackSelector:nil object:nil];
    NSLog(@"registrationID = %@", [APService registrationID]);
    //==============================JPush===============================================
    
    
    self.navc = [HOTNavigationViewController createNaviWithRootViewController:self.menuVC];
    self.window.rootViewController = self.navc;
    [self.window makeKeyAndVisible];
    return YES;
}

#pragma mark - JPush
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // Required
    [APService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required
    [APService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [APService handleRemoteNotification:userInfo];
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    NSLog(@"聊天消息 %@" ,userInfo);
    
    //NSData *respones = [[notification.userInfo objectForKey:@"content"] dataUsingEncoding:NSUTF8StringEncoding];
    //id jsonObject = [NSJSONSerialization JSONObjectWithData:[notification.userInfo objectForKey:@"content"] options:NSJSONReadingAllowFragments error:nil];
    
    [[HOTMessageHandler handler] handleMessageNotification:userInfo];
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    [APService showLocalNotificationAtFront:notification identifierKey:nil];
}

#pragma mark - JPush 通知

- (void)networkDidSetup:(NSNotification *)notification {

    NSLog(@"已连接");
}

- (void)networkDidClose:(NSNotification *)notification {

    NSLog(@"未连接。。。");
}

- (void)networkDidRegister:(NSNotification *)notification {

    NSLog(@"已注册");
    
}

- (void)networkDidLogin:(NSNotification *)notification {

    NSLog(@"已登录");
    
    [APService setTags:nil alias:[APService registrationID] callbackSelector:nil object:nil];
    
    HOTUserInfo *userInfo = [HOTUserInfo defaultUser];
    
    userInfo.push_token = [APService registrationID];
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:
(UIUserNotificationSettings *)notificationSettings {
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
}
#endif

//- (void)networkDidReceiveMessage:(NSNotification *)notification {
//    //接收到非APNS的消息
//    
//    //[self parseMessageWithNotification:notification];
//    NSLog(@"聊天消息 %@" ,[notification.userInfo objectForKey:@"content"]);
//    
//    //NSData *respones = [[notification.userInfo objectForKey:@"content"] dataUsingEncoding:NSUTF8StringEncoding];
//     //id jsonObject = [NSJSONSerialization JSONObjectWithData:[notification.userInfo objectForKey:@"content"] options:NSJSONReadingAllowFragments error:nil];
//    
//    [[HOTMessageHandler handler] handleMessageNotification:[notification.userInfo objectForKey:@"content"]];
//}

/*
-(void)parseMessageWithNotification:(NSNotification *)notification {
    
    NSDictionary * userInfo = [notification userInfo];
    NSString *type = [userInfo valueForKey:@"type"];
    
    if ([HOTUtils isNotNullOrEmpty:type]) {
        
        if ([type isEqualToString:@"article_repied"]) {
            //自己的投稿被回复时
            
        } else if ([type isEqualToString:@"was_followed"]) {
            //被别人设置为 “知り合い’”
            
        } else if ([type isEqualToString:@"new_msg_incoming"]) {
            //Message聊天里来新消息时
            
        } else if ([type isEqualToString:@"system_msg_incoming"]) {
            //后台运营方发来的系统通知 “お知らせ” 时
            
        }
    }
}
 */

-(void)createRegion {
    
    NSString *regionStr = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"zenkoku" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];
    
    NSArray *regionArr = [regionStr componentsSeparatedByString:@"\n"];
    
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
    
    NSMutableArray *multiArr = [[NSMutableArray alloc] initWithCapacity:10];
    int idIndex = 1;
    for (NSString *str in regionArr) {
        
        NSArray *subArr = [str componentsSeparatedByString:@","];
        
        if (subArr.count != 2) {
            
            NSLog(@"is wrong = %@", str);
            continue;
        }
        
        for (int i=0;i < subArr.count; i ++) {
            
            if (i == 0) {
                
                NSString *existIndex = [tempDic objectForKey:[subArr objectAtIndex:i]];
                if (existIndex) {
                    
                    //NSMutableDictionary *dic = [multiArr objectAtIndex:[existIndex intValue]];
                    
                } else {
                    
                    NSString *key = [subArr objectAtIndex:i];
                    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                    //[dic setObject:multiArr.count forKey:[subArr objectAtIndex:i]];
                    [dic setObject:key forKey:@"name"];
                    [dic setObject:[NSString stringWithFormat:@"%d", idIndex++] forKey:@"id"];
                    NSMutableArray *newArr = [NSMutableArray array];
                    [dic setObject:newArr forKey:@"list"];
                    
                    [tempDic setObject:[NSString stringWithFormat:@"%d", multiArr.count] forKey:key];
                    [multiArr addObject:dic];
                    
                }
            } else {
                
                NSString *existIndex = [tempDic objectForKey:[subArr objectAtIndex:0]];
                if (existIndex) {
                    
                    NSMutableDictionary *dic = [multiArr objectAtIndex:[existIndex intValue]];
                    NSMutableArray *newArr = [dic objectForKey:@"list"];
                    
                    NSString *str = [subArr objectAtIndex:1];
                    if ([str rangeOfString:@"\r"].length >0) {
                        str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                    }
                    [newArr addObject:str];

                } else {
                    
                    NSLog(@"existIndex 不存在 %@", str);
                }
            }
        }
    }
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths firstObject];
    path = [path stringByAppendingString:@"/zenkoku.plist"];
    NSLog( @"%@", path);
    [multiArr writeToFile:path atomically:YES];
}


-(void)createJobTypePlist {
    
    NSArray *arr = @[@"土木工事業",
                     @"建築工事業",
                     @"大工工事業",
                     @"左官工事業",
                     @"とび・土工工事業",
                     @"石工事業",
                     @"屋根工事業",
                     @"電気工事業",
                     @"管工事業",
                     @"タイル・れんが・ブ ロック工事業",
                     @"鋼構造物工事業",
                     @"鉄筋工事業",
                     @"ほ装工事業",
                     @"しゅんせつ工事業",
                     @"板金工事業",
                     @"ガラス工事業",
                     @"塗装工事業",
                     @"防水工事業",
                     @"内装仕上工事業",
                     @"機械器具設置工 事業",
                     @"熱絶縁工事業",
                     @"電気通信工事業",
                     @"造園工事業",
                     @"さく井工事業",
                     @"建具工事業",
                     @"水道施設工事業",
                     @"消防施設工事業",
                     @"清掃施設工事業",
                     @"設計事業",
                     @"デザイン事業",
                     @"その他"
                     ];
    NSMutableArray *plist = [[NSMutableArray alloc] init];
    for (int i =1;  i <= arr.count; i ++) {
        
        NSString *jName = [arr objectAtIndex:i-1];
        NSDictionary *dic = @{@"jid":@(i), @"jname":jName};
        
        [plist addObject:dic];
    }
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths firstObject];
    path = [path stringByAppendingString:@"/jobType"];
    NSLog( @"%@", path);
    [plist writeToFile:path atomically:YES];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    
    //检测版本更新
    [[Harpy sharedInstance] checkVersion];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
